import { NextApiRequest, NextApiResponse } from 'next'
import {withIronSessionApiRoute} from 'iron-session/next'
import {prepareConnection} from 'db/index'
import { User,Article,Tag } from 'db/entity/index'
import {ironOptions} from 'config/index'
import { ISession} from 'pages/api/index'
import { EXCEPTION_ARTICLE } from 'pages/api/config/codes'

export default withIronSessionApiRoute(publish,ironOptions)

async function publish(req: NextApiRequest, res: NextApiResponse) {
    const sesssion: ISession = req.session
    const {title='',content='',tagIds=[]} = req.body
    // 连接数据库
    const db = await prepareConnection()
    const articleRepo = db.getRepository(Article)
    const userRepo = db.getRepository(User)
    const tagRepo = db.getRepository(Tag)
    // 判断用户是否登录，未登录则返回错误
    const user = await userRepo.findOne({id: sesssion.userId})
    const tags = await tagRepo.find({
        where: tagIds?.map((tagId:number) => ({id: tagId})),
    })
    // 操作数据库，写入数据
    const article = new Article()
    article.title = title
    article.content = content
    article.create_time = new Date()
    article.update_time = new Date()
    article.is_delete = 0
    article.views = 0
    // 判断用户是否存在，存在则将数据关联到用户
    if(user){
        article.user = user
    }
    // 判断标签是否存在，存在则将数据关联到标签
    if(tags){
        const newTags = tags?.map(tag => {
            tag.article_count = tag?.article_count + 1
            return tag
        })
        console.log(newTags,123)
        article.tags = newTags
    }
    // 保存数据
    const resArticle = await articleRepo.save(article)
    if(resArticle){
        // 返回数据
        res?.status(200).json({code:0,msg:'发布成功',data:resArticle})
    }else{
        // 返回错误
        res?.status(200).json({...EXCEPTION_ARTICLE.PUBLISH_FAILED})
    }
}